<template>
  <div class="news-management">
    <h3 class="title">新闻管理区域</h3>
    <table class="news-table">
      <thead>
        <tr>
          <th>编号</th>
          <th>标题</th>
          <th>作者</th>
          <th>图片</th>
          <th>出版日期</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in news" :key="item.id">
          <td>{{ item.newid }}</td>
          <td>{{ item.title }}</td>
          <td>{{ item.author }}</td>
          <td>{{ item.imageName }}</td>
          <td>{{ item.publishdate }}</td>
          <td><a href="javascript:;" @click="goDetail(item.newid)" class="delete-btn">删除</a></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios'


const news = ref([])
const errorMessage = ref('')

const fetchNews = async () => {
    try {
        const response = await axios.get('http://localhost:3001/getNews')
        news.value = response.data
        errorMessage.value = ''  // 清空错误信息
    } catch (error) {
        console.error('获取数据时发生错误:', error)
        errorMessage.value = '加载数据失败，请稍后再试。'
    }
}
const goDetail = async (id) => {
    try {
        const response = await axios.get(`http://localhost:3001/deleteNews?id=${id}`)
        news.value = response.data
        errorMessage.value = ''  // 清空错误信息
        window.location.reload();
    } catch (error) {
        console.error('获取数据时发生错误:', error)
        errorMessage.value = '加载数据失败，请稍后再试。'
    }
}
// 自动切换功能
onMounted(fetchNews)
</script>

<style scoped>
.news-management {
  margin: 20px;
  font-family: 'Arial', sans-serif;
}

.title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.news-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.news-table th,
.news-table td {
  padding: 12px 15px;
  text-align: center;
  border: 1px solid #ddd;
}

.news-table th {
  background-color: #f4f4f4;
  color: #555;
  font-weight: bold;
}

.news-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.news-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 5px;
}

.delete-btn {
  color: #f44336;
  text-decoration: none;
  font-weight: bold;
  padding: 5px 10px;
  border: 1px solid #f44336;
  border-radius: 4px;
  transition: background-color 0.3s, color 0.3s;
}

.delete-btn:hover {
  background-color: #f44336;
  color: white;
}
</style>